package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.AlertDataVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService
{
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 查询报警数据
     * 
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     * 
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertDataVo> selectAlertDataList(AlertData alertData) {
        //获得当前线程的用户id
        Long userId = SecurityUtils.getUserId();
        //根据当前用户id查询报警数据
        List<AlertData> alertDataList = new ArrayList<>();
        if(userId.equals(1L)){
            alertDataList = alertDataMapper.selectList(Wrappers.<AlertData>lambdaQuery()
                    .eq(ObjectUtil.isNotEmpty(alertData.getStatus()),AlertData::getStatus,alertData.getStatus()));
        }else{
            alertDataList = alertDataMapper.selectList(Wrappers.<AlertData>lambdaQuery()
                    .eq(AlertData::getUserId, userId)
                    .eq(ObjectUtil.isNotEmpty(alertData.getStatus()),AlertData::getStatus,alertData.getStatus()));
        }
        List<AlertDataVo> list = new ArrayList<>();
        alertDataList.forEach(alertData1 ->{
            AlertDataVo alertDataVo = BeanUtil.toBean(alertData1, AlertDataVo.class);
            String iotId = alertData1.getIotId();
            Device one = deviceService.getOne(Wrappers.<Device>lambdaQuery()
                    .eq(Device::getIotId, iotId));
            alertDataVo.setNickName(one.getNodeId());
            list.add(alertDataVo);
        });
        return list;

    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData)
    {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void handleAlerData(AlertDataDto alertDataDto) {
        //获取当前处理人的id
        Long userId = SecurityUtils.getUserId();
        AlertData alertData = alertDataMapper.selectOne(Wrappers.<AlertData>lambdaQuery()
                .eq(AlertData::getUserId, userId)
                .eq(AlertData::getId,alertDataDto.getId()));
        //根据处理人id获取处理人的信息
        SysUser sysUser = userService.selectUserById(userId);
        //处理时间格式
        String processingTime = alertDataDto.getProcessingTime();
        // 使用 Java 8 DateTime API 转换格式
        LocalDateTime dateTime = Instant.parse(processingTime)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        // 转换为 MySQL 兼容格式（无时区）
        String mysqlDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        this.update(Wrappers.<AlertData>lambdaUpdate()
                .eq(AlertData::getId,alertDataDto.getId())
                .set(AlertData::getProcessorId,userId)
                .set(AlertData::getProcessorName,sysUser.getUserName())
                .set(AlertData::getProcessingTime,mysqlDateTime)
                .set(AlertData::getStatus,1)
                .set(AlertData::getProcessingResult,alertDataDto.getProcessingResult()));

        //当前用户处理完报警数据之后，更改表中数据让所有人看到处理结果
        String iotId = alertData.getIotId();
        List<AlertData> alertDataList = alertDataMapper.selectList(Wrappers.<AlertData>lambdaQuery()
                .eq(AlertData::getIotId, iotId));
        alertDataList.forEach(alertData1 -> {
            this.update(Wrappers.<AlertData>lambdaUpdate()
                    .eq(AlertData::getIotId,iotId)
                    .eq(AlertData::getCreateTime,alertData.getCreateTime())
                    .set(AlertData::getProcessorId,userId)
                    .set(AlertData::getProcessorName,sysUser.getUserName())
                    .set(AlertData::getProcessingTime,mysqlDateTime)
                    .set(AlertData::getStatus,1)
                    .set(AlertData::getProcessingResult,alertDataDto.getProcessingResult()));
        });
    }


}
